<script lang="ts" setup>
// #region 引入包, 函数和组件
// import { ref } from "vue"
import { infoEchartsApi } from '@/business'
import type { InfoEchartsData } from '@/interfaces/RequestType'
import * as echarts from 'echarts'
import type { CallbackDataParams } from 'echarts/types/dist/shared'
import { ref, watch } from 'vue'
type EChartsOption = echarts.EChartsOption
// #endregion

// #region // 使用模块(仓库、路由、父组件参数函数)

// #endregion

// #region // 变量
const chart1 = ref<HTMLDivElement | null>(null)
const option = ref<EChartsOption>({})
const infoDashoard = ref<InfoEchartsData[]>([])
// Request.post('/info/dashoard').then(res => console.log(res))
// #endregion

// #region // 函数
const resize = (myChart: echarts.ECharts) => {
  myChart.resize()
  // console.log(111)
}
// 获取图表信息
const getInfoEcharts = async () => {
  try {
    const res = await infoEchartsApi()
    // console.log(res.data.data.result)
    infoDashoard.value = res.data.data.result
  } catch (error) {
    console.log(error)
  }
}
const initChart1 = () => {
  // console.log(chart1.value)
  const myChart = echarts.init(chart1.value)
  const xName = infoDashoard.value.map(v => v.name)

  const grid = {
    left: 100,
    right: 100,
    top: 50,
    bottom: 50,
  }
  const series: echarts.BarSeriesOption[] = Object.keys(infoDashoard.value[0].score).map((name) => {
    return {
      name,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      label: {
        show: true,
        formatter: (params: CallbackDataParams) =>
          params.value as number + '分'
      },
      data: infoDashoard.value.map(item => item.score[name]),
    }
  })

  option.value = {
    legend: {
      selectedMode: true,
    },
    grid,
    yAxis: {
      type: 'value',
    },
    xAxis: {
      type: 'category',
      data: xName
    },
    series,
  }

  if (option.value) myChart.setOption(option.value)

  window.addEventListener('resize', () => {
    // console.log(111)
    resize(myChart)
  })
}
// #endregion

// #region // 生命周期和vue函数
getInfoEcharts()
watch([() => infoDashoard.value, () => chart1], (nval) => {
  if (nval[0] && nval[1]) {
    // console.log(nval)
    initChart1()
  }
})

// #endregion
</script>

<template>
  <div class="info_dashoard">
    <el-row>
      <el-col :span="24">
        <div class="chart1" ref="chart1"></div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="sass" scoped>
.el-row
  width: 100%
  height: 50%
.chart1
  width: 100%
  height: 100%
</style>
